import 'package:date_format/date_format.dart';
import 'package:flutter/material.dart';
import 'package:flutter_picker/flutter_picker.dart';
import 'package:tender_flutter/constant/theme_colors.dart';
import 'package:tender_flutter/page/common/api/api_common.dart';
import 'package:tender_flutter/page/home/model/city_entity.dart';

typedef StringClickCallback = void Function(int selectIndex, Object selectStr);
typedef ArrayClickCallback = void Function(
    List<int> selecteds, List<dynamic> strData);
typedef DateClickCallback = void Function(
    dynamic selectDateStr, dynamic selectDate);
typedef CityClickCallback = void Function(
    List<int> selectCodes, dynamic selectCity);

enum DateType {
  YM,
  YMD_HM,
  YMD_AP_HM,
}

double kPickerHeight = 216.0;
double kItemHeight = 40.0;
Color kBtnColor = ThemeColors.colorType6;
Color kTitleColor = ThemeColors.colorType1;
double kTitleFontSize = 17.0;
double kBtnFontSize = 15.0;

class PickerUtils<T> {
  /// 单列选择器
  static void showStringPicker<T>(
    BuildContext context, {
    @required List<T> data,
    String title,
    int normalIndex,
    PickerDataAdapter adapter,
    @required StringClickCallback clickCallBack,
  }) {
    openModalPicker(context,
        adapter: adapter ?? PickerDataAdapter(pickerdata: data, isArray: false),
        clickCallBack: (Picker picker, List<int> selecteds) {
      clickCallBack(selecteds[0], data[selecteds[0]]);
    }, selecteds: [normalIndex ?? 0], title: title);
  }

  /// 多列选择器
  static void showArrayPicker<T>(
    BuildContext context, {
    @required List<T> data,
    String title,
    List<int> normalIndex,
    PickerDataAdapter adapter,
    @required ArrayClickCallback clickCallBack,
  }) {
    openModalPicker(context,
        adapter: adapter ?? PickerDataAdapter(pickerdata: data, isArray: true),
        clickCallBack: (Picker picker, List<int> selecteds) {
      clickCallBack(selecteds, picker.getSelectedValues());
    }, selecteds: normalIndex, title: title);
  }

  static void openModalPicker(
    BuildContext context, {
    @required PickerAdapter adapter,
    String title,
    List<int> selecteds,
    @required PickerConfirmCallback clickCallBack,
  }) {
    new Picker(
            adapter: adapter,
            title: new Text(title ?? "请选择",
                style: TextStyle(color: kTitleColor, fontSize: kTitleFontSize)),
            selecteds: selecteds,
            cancelText: '取消',
            confirmText: '确定',
            cancelTextStyle:
                TextStyle(color: kBtnColor, fontSize: kBtnFontSize),
            confirmTextStyle:
                TextStyle(color: kBtnColor, fontSize: kBtnFontSize),
            textAlign: TextAlign.right,
            itemExtent: kItemHeight,
            height: kPickerHeight,
            selectedTextStyle: TextStyle(color: Colors.black),
            onConfirm: clickCallBack)
        .showModal(context);
  }

  /// 日期选择器
  static void showDatePicker(
    BuildContext context, {
    DateType dateType,
    String title,
    DateTime maxValue,
    DateTime minValue,
    DateTime value,
    DateTimePickerAdapter adapter,
    @required DateClickCallback clickCallback,
  }) {
    int timeType;
    if (dateType == DateType.YM) {
      timeType = PickerDateTimeType.kYM;
    } else if (dateType == DateType.YMD_HM) {
      timeType = PickerDateTimeType.kYMDHM;
    } else if (dateType == DateType.YMD_AP_HM) {
      timeType = PickerDateTimeType.kYMD_AP_HM;
    } else {
      timeType = PickerDateTimeType.kYMD;
    }

    openModalPicker(context,
        adapter: adapter ??
            DateTimePickerAdapter(
              type: timeType,
              isNumberMonth: true,
              yearSuffix: "年",
              monthSuffix: "月",
              daySuffix: "日",
              strAMPM: const ["上午", "下午"],
              maxValue: maxValue,
              minValue: minValue,
              value: value ?? DateTime.now(),
            ),
        title: title, clickCallBack: (Picker picker, List<int> selecteds) {
      var time = (picker.adapter as DateTimePickerAdapter).value;
      var timeStr;
      if (dateType == DateType.YM) {
        timeStr = time.year.toString() + "年" + time.month.toString() + "月";
      } else if (dateType == DateType.YMD_HM) {
        timeStr = time.year.toString() +
            "年" +
            time.month.toString() +
            "月" +
            time.day.toString() +
            "日" +
            time.hour.toString() +
            "时" +
            time.minute.toString() +
            "分";
      } else if (dateType == DateType.YMD_AP_HM) {
        var str = formatDate(time, [am]) == "AM" ? "上午" : "下午";
        timeStr = time.year.toString() +
            "年" +
            time.month.toString() +
            "月" +
            time.day.toString() +
            "日" +
            str +
            time.hour.toString() +
            "时" +
            time.minute.toString() +
            "分";
      } else {
        timeStr = time.year.toString() +
            "年" +
            time.month.toString() +
            "月" +
            time.day.toString() +
            "日";
      }
//          print(formatDate(DateTime(1989, 02, 21), [yyyy, '-', mm, '-', dd]));
      clickCallback(timeStr, time);
    });
  }

  /// 城市选择器
  static showCityPicker(BuildContext context,
      {String title,
      List<int> normalIndexs,
      PickerDataAdapter adapter,
      @required CityClickCallback clickCallBack}) async {
    /// 解析省市区
    List<CityEntity> cityDatas = await ApiCommon.getCityDatas();
    List pickerDatas = [];
    for (int i = 0; i < cityDatas.length; i++) {
      var province = cityDatas[i];
      // 省市两级
      pickerDatas
          .add({province.title: province.areas.map((e) => e.title).toList()});
      // 省市区三级
      // pickerDatas.add({
      //   province.title: province.areas
      //       .map((e) => {e.title: e.areas.map((e) => e.title).toList()})
      //       .toList()
      // });
    }

    Picker picker = new Picker(
        adapter: adapter ?? PickerDataAdapter<String>(pickerdata: pickerDatas),
        changeToFirst: true,
        title: new Text(title ?? "请选择",
            style: TextStyle(color: kTitleColor, fontSize: kTitleFontSize)),
        selecteds: normalIndexs,
        cancelText: '取消',
        confirmText: '确定',
        cancelTextStyle: TextStyle(color: kBtnColor, fontSize: kBtnFontSize),
        confirmTextStyle: TextStyle(color: kBtnColor, fontSize: kBtnFontSize),
        textAlign: TextAlign.right,
        itemExtent: kItemHeight,
        height: kPickerHeight,
        selectedTextStyle: TextStyle(color: Colors.black),
        onConfirm: (Picker picker, List value) {
          List<int> cityCodes = [];

          if (value.length > 0) {
            cityCodes.add(cityDatas[value[0]].id);
          }
          if (value.length > 1) {
            cityCodes.add(cityDatas[value[0]].areas[value[1]].id);
          }
          if (value.length > 2) {
            cityCodes
                .add(cityDatas[value[0]].areas[value[1]].areas[value[2]].id);
          }

          print(cityCodes.toString());
          print(picker.getSelectedValues());
          clickCallBack(cityCodes, picker.getSelectedValues().join("-"));
        });
    picker.showModal(context);
  }
}
